﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO.Compression;
using BadmintonBuddy.Models;
using System.Text;


namespace BadmintonBuddy.Controllers
{
    public class CompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }


    public class Log
    {
        
        public static void WriteLog(ClubRepository repository, LogType type, string LogMessage)
        {
            repository.Log((int)type, LogMessage);
        }

        public static void WriteException(ClubRepository repository, Exception ex)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<root>");
            builder.Append("<exception>");
            builder.Append(ex.Message);
            builder.Append("</exception>");
            builder.Append("<stacktrace>");
            builder.Append(ex.StackTrace);
            builder.Append("</stacktrace>");
            builder.Append("</root>");
            repository.Log((int)LogType.Exception, builder.ToString());
        }

        public static void WriteException(ClubRepository repository, Exception ex,string customMessage)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<root>");
            builder.Append("<source>");
            builder.Append(customMessage);
            builder.Append("</source>");
            builder.Append("<exception>");
            builder.Append(ex.Message);
            builder.Append("</exception>");
            builder.Append("<stacktrace>");
            builder.Append(ex.StackTrace);
            builder.Append("</stacktrace>");
            builder.Append("</root>");
            repository.Log((int)LogType.Exception, builder.ToString());
        }

    }

    public enum LogType
    {
        ReportProblem=1,
        Feedback,
        MoreDetails,
        Exception
    }
}
